package org.java.test;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.UUID;

import org.junit.Test;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DemoExample{
	/**
	 * 字符串BASE64编码解码
	 */
	@Test
	public void charCodeTest(){
		BASE64Encoder encoder=new BASE64Encoder();
		BASE64Decoder decoder=new BASE64Decoder();
		String encodeStr=null;
		String decodeStr=null;
		String originStr="字符串BASE64编码解码";
		byte[] arrs=null;
		try {
			System.out.println("源字符串："+originStr);
			encodeStr = encoder.encode(originStr.getBytes("utf-8"));
			System.out.println("编码后："+encodeStr);
			arrs=decoder.decodeBuffer(encodeStr);
			decodeStr=new String(arrs,"utf-8");
			System.out.println("解码后："+decodeStr);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	/**
	 * 针对JS客户端的encodeURI或者encodeURIComponent编码，get请求获取参数new String(userName.getBytes("ISO8859-1"),"UTF-8")
	 * java后台解码方法
	 * 如果还是乱码则需在客户端使用两次encodeURI方法，例如encodeURI(encodeURI("中文"))，第一次是把中文编码成%E5的格式， 第二次是对%E5中的%进行编码,%编码成%25。
	 * 原因：在浏览器地址栏里，浏览器认为%是个转义字符，浏览器会把%与%之间两位两位取出后进行编码,然后再传递给处理页面。
	 */
	@Test
	public void addrURL(){
		String origin="%E5%AD%A6%E7%B1%8D%E7%AE%A1%E7%90%86-%E5%AD%A6%E7%B1%8D%E7%99%BB%E8%AE%B0-%E9%A3%9F%E5%93%81%E7%A7%8D%E7%B1%BB%E6%88%90%E4%BB%BD%E7%99%BB%E8%AE%B0";
		try {
			origin = new String(origin.getBytes("iso-8859-1"),"utf-8");
			String ss=URLDecoder.decode(origin, "utf-8");
			System.out.println("解码后:"+ss);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 针对JS客户端的escape编码，java后台解码方法
	 */
	@Test
	public void unescape(){
		String src="%u4E0A%u6D77%u5362%u6E7E";
		///////////////开始/////////////////////
		StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        ////////////////结束////////////////////////
        System.out.println("=====escape解码后："+tmp.toString());
	}
	/**
	 * 通用唯一标识码UUID
	 */
	@Test
	public void createUUID(){
		UUID uuid = UUID.randomUUID();
		String id=uuid.toString().toUpperCase();
		System.out.println("唯一标识码:"+id);
	}
	/**
	 * MD5加密
	 */
	@Test
	public void md5Encrypt(){
		MessageDigest md=null;
		String originStr="MD5加密";
		String encStr=null;
		try {
			md=MessageDigest.getInstance("md5");
			encStr=md.digest(originStr.getBytes()).toString();
			System.out.println("加密后数据："+encStr);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 控制double精度,四舍五入
	 * b.setScale(scale,roundingMode);
	 * scale表示小数位数(精度)
	 * roundingMode表示舍入模式(枚举RoundingMode.HALF_UP:四舍五入)
	 */
	@Test
	public void round(){
		BigDecimal bg=new BigDecimal(0.5572963294538943*100);
		bg=bg.setScale(2, RoundingMode.HALF_UP);
		System.out.println(bg.doubleValue());
	}
	/**
	 * 格式化百分比(percent)
	 */
	@Test
	public void getPercent() {
		NumberFormat nf = NumberFormat.getPercentInstance();
		nf.setMaximumIntegerDigits(3);//设置整数部分所允许的最大位数
		nf.setMaximumFractionDigits(2);//设置小数部分所允许的最大位数(精度:四舍五入)
		Double d = Double.valueOf(12.45) / Double.valueOf(22.34);
		System.out.println("NumberFormat采用的舍入模式=="+nf.getRoundingMode());
		System.out.println("格式前:"+d+"\n格式后:"+nf.format(d));
	}
	/**
	 * 字符串输出流
	 */
	@Test
	public void stringWriter(){
//		StringWriter sw=new StringWriter();//StringWriter为底层流，目标区dest为其缓存区
//		sw.write("我是中国人");
//		System.out.println(sw.toString());
		OutputStreamWriter wr= new OutputStreamWriter(System.out);
		int i=5;
		i<<=2;//左移位，i乘以2的n次幂,输出i=20
		try {
			wr.write("我是中国人");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	/**
	 * 读取文件资源束
	 * @param args
	 */
	@Test
	public  void readResourceFile() {
		//ResourceBundle rb=ResourceBundle.getBundle("org.practice.control.OgnlAction");
		ResourceBundle rb=ResourceBundle.getBundle("org\\practice\\control\\OgnlAction");
		Enumeration<String> en=rb.getKeys();
		while(en.hasMoreElements()){
			String key=en.nextElement();
			String value=rb.getString(key);
			//map.put(key,value);
			System.out.println("value===="+value);
		}
	}
	/**
	 * Unicode转义字符后面必须是四位0~F的十六进制,\u000a表示换行,相当于\n。Java中直接将Unicode转义字符替换成相应字符
	 * 特殊字符的转义字符：\n表换行,\\表示字符\
	 * 字符串分割,StringTokenizer
	 */
	@Test
	public void splitString(){
		String str="name:zhangsan|sex:男|age:10";
		//字符'|'和'.'是正则表达式的特殊字符，在正则表达式中需要加反斜杠转义,反斜扛在编译器下也是个特殊字符，也需要加反斜杠转义
		StringTokenizer st=new StringTokenizer(str,"\\|");
		while(st.hasMoreTokens()){
			String ss=st.nextToken();
			System.out.println(ss);
			String[] strArray=ss.split(":");
			for(String s:strArray){
				System.out.println(s.toString());
			}
		}
	}
}
